package com.chenqi.utils;

import com.chenqi.model.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * @description: jwt令牌生产工具类
 * @program: ardaicommunity
 * @author: ChenQi
 * @create: 2021-03-2021/3/9-14-36
 */
public class JwtUtils {
    //令牌的一些基本属性
    /**
     * 过期时间
     */
    private static  final  long EXPIRE = 60000 * 60 * 24 * 7;
    /**
     * 密钥
     */
    private static  final String SECRET = "ardai.com";
    /**
     * 令牌前缀
     */
    private static  final  String TOKEN_PREFIX = "ardai";
    /**
     * subject
     */
    private static  final String SUBJECT = "ardai";

    /**
     * 根据用户信息生产令牌
     * @param user
     * @return
     */
    public static String geneJsonWebToken(User user) {
        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("id", user.getId())
                .claim("username", user.getUsername())
                .claim("avatar", user.getAvatar())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis()+EXPIRE))
                .signWith(SignatureAlgorithm.HS256,SECRET).compact();
        token =TOKEN_PREFIX+token;
        return token;
    }

    /**
     * 校验token的代码
     * @param token
     * @return
     */
    public static Claims checkJWT(String token) {
        try{
            final Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token.replace(TOKEN_PREFIX, "")).getBody();
            return claims;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

}
